<template>
  <div class="parent-div">
    <el-card>
      <el-form :model="loginForm">
        <el-form-item label="用户名:">
          <el-input v-model="loginForm.name" placeholder="请输入学工号或邮箱或姓名"/>
        </el-form-item>
        <el-form-item label="密码:">
          <el-input v-model="loginForm.pwd" placeholder="请输入密码" show-password/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import axios from "axios";
import {onMounted, reactive} from "vue";
import {ElNotification} from "element-plus";

const failureNotification = (msg = '请刷新页面重新提交，或将页面正文中信息复制发给社长') => {
  ElNotification({
    title: '提交失败',
    message: msg,
    type: 'error',
    duration: 0,
  })
}

const loginForm = reactive({
  name: '',
  pwd: '',
})

onMounted(() => {
  if(localStorage.username !== undefined && localStorage.stuID !== undefined) {
    window.location.href = window.location.origin + '#/guide'
  }
})

const submit = () => {
  let data_ = new FormData();
  data_.append('name', loginForm.name)
  data_.append('pwd', loginForm.pwd)
  axios.post('/api/login', data_)
  .then(res => {
    let result = res.data;
    if(res.status === 200) {
      localStorage.token = result['refresh_token']
      localStorage.username = result['name']
      localStorage.stuID = result['id']
      localStorage.type = result['type']
      localStorage.phone = result['phone']
      window.location.href = window.location.origin + '#/guide'
    }else {
      failureNotification(result)
    }
  }).catch(e => {
    failureNotification(e.response.data)
  })
}



</script>

<style scoped>
.parent-div {
  display: flex;
  flex-direction: column;
  justify-content: center;
}
el-card {
  margin-left: auto;
  margin-right: auto;
}
</style>